// src/utils/qiankunState.ts
import { ref } from 'vue'
interface BudgetState {
  pageState: Recordable
}

// 存储当前状态
const currentState = ref<Recordable>({})

// 定义 props 类型
interface QiankunProps {
  setGlobalState: (state: BudgetState) => void
  onGlobalStateChange?: (callback: (state: Recordable, prev: Recordable) => void) => void
}

// 存储 qiankun props
const qiankunProps = ref<QiankunProps>()

// 设置 props
export const setQiankunProps = (props: QiankunProps) => {
  qiankunProps.value = props
}

// 设置全局状态
export const setComponentsState = (currentPath: string, value: any) => {
  // 使用存储的上一个路由路径
  if (currentPath) {
    currentState.value[currentPath] = value
    qiankunProps.value?.setGlobalState({
      pageState: currentState.value
    })
  }
}

// 主应用变更缓存时，直接替换缓存
export const setComponentsStateByMain = (value: any) => {
  currentState.value = value
}

// 获取当前状态
export const getComponentsState = (componentName: string | undefined) => {
  if (!componentName) {
    return currentState.value
  }
  return currentState.value[componentName]
}
